package common;

import java.util.StringTokenizer;

public class Utils{
	public static void printIp( long ip ){
		System.out.print( ipToString( ip ) );
	}
	
	public static String ipToString( long ip ){
		long classA = ip / 256 / 256 / 256;
		long classB = ip / 256 / 256 % 256;
		long classC = ip / 256 % 256;
		long classD = ip % 256;
		
		return new String( classA + "." + classB + "." + classC + "." + classD );
	}
	
	public static long stringToIp( String s ){
		long classA, classB, classC, classD;
		StringTokenizer st = new StringTokenizer( s, "." ); 
		
		if( st.countTokens() != 4 )
			return -1;

		try{
			classA = Long.parseLong( st.nextToken() );
			classB = Long.parseLong( st.nextToken() );
			classC = Long.parseLong( st.nextToken() );
			classD = Long.parseLong( st.nextToken() );
		}catch( NumberFormatException e ){
			e.printStackTrace();
			return -1;
		}
		
		return ( ( classA * 256 + classB ) * 256 + classC ) * 256 + classD;
	}
	
	public static boolean isNumber( String s ){
		try{
			Double.parseDouble( s );
		}catch( NumberFormatException e ){
			return false;
		}
		return true;
	}
	
	// dump wrapper
	public static void print_log( String log ){
		print_log( log, Def.STDOUT );
	}
	
	public static void print_log( String log, byte target ){
		if( !Conf.VERBOSE )
			return;
		
		if( target == Def.STDOUT ){
			//System.out.print( "[MSG|" + pid + ":" + Utils.ipToString( ip ) + "(" + localtime_s + ")] " );
			System.out.println( log );
		}else if( target == Def.STDERR ){
			//System.err.print( "[ERR|" + pid + ":" + Utils.ipToString( ip ) + "(" + localtime_s + ")] " );
			System.err.println( log );
		}
	}
}//end-of-class
